package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.DocumentAdapter;
import flc.ast.bean.MyDocumentBean;
import flc.ast.databinding.ActivityDocumentBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.media.MediaInfo;
import stark.common.basic.media.MediaLoader;
import stark.common.basic.utils.RxUtil;

public class DocumentActivity extends BaseAc<ActivityDocumentBinding> {

    private DocumentAdapter documentAdapter;
    private boolean isEdit = false;
    private List<String> listUri = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.activity_document;
    }

    @Override
    public void onBackPressed() {
        if (isEdit) {
            cancelEdit();
        } else {
            finish();
        }
    }

    @Override
    protected void initView() {
        mDataBinding.ivDocumentBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivDocumentEdit.setOnClickListener(this);
        mDataBinding.tvDocumentDelete.setOnClickListener(this);

        mDataBinding.rvDocumentList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        documentAdapter = new DocumentAdapter();
        mDataBinding.rvDocumentList.setAdapter(documentAdapter);
        documentAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivDocumentEdit://编辑
                isEdit = true;
                mDataBinding.ivDocumentEdit.setVisibility(View.GONE);
                mDataBinding.tvDocumentDelete.setVisibility(View.VISIBLE);
                documentAdapter.setEdit(isEdit);
                documentAdapter.notifyDataSetChanged();
                mDataBinding.tvDocumentDelete.setText(getString(R.string.delete_text, listUri.size()));
                break;
            case R.id.tvDocumentDelete://删除
                if (listUri.size() == 0) return;
                deleteDoc();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (documentAdapter.getItem(position).isSelect()) {
                documentAdapter.getItem(position).setSelect(false);
                listUri.remove(documentAdapter.getItem(position).getUri());
            } else {
                documentAdapter.getItem(position).setSelect(true);
                listUri.add(documentAdapter.getItem(position).getUri());
            }
            documentAdapter.notifyItemChanged(position);
            mDataBinding.tvDocumentDelete.setText(getString(R.string.delete_text, listUri.size()));
        } else {
            gotoPreviewDoc(documentAdapter.getItem(position).getUri());
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    //获取文档数据
    private void getData() {
        //设置获取的数据类型 只获取pdf
        List<String> type = new ArrayList<>();
        type.add("application/msword");
        type.add("application/vnd.ms-excel");
        type.add("application/vnd.ms-powerpoint");
        type.add("application/pdf");
        type.add("text/plain");
        RxUtil.create(new RxUtil.Callback<List<MediaInfo>>() {
            @Override
            public void doBackground(ObservableEmitter<List<MediaInfo>> emitter) {
                List<MediaInfo> infoList = MediaLoader.loadDoc(type);
                emitter.onNext(infoList);
            }

            @Override
            public void accept(List<MediaInfo> selectMediaEntities) {
                List<MyDocumentBean> listDocument = new ArrayList<>();
                if (selectMediaEntities.size() > 0) {
                    for (MediaInfo bean : selectMediaEntities) {
                        listDocument.add(new MyDocumentBean(bean.getName(), bean.getPath(), bean.getUri()
                                , bean.getSize()
                                , TimeUtils.millis2String(FileUtils.getFileLastModified(bean.getPath()), "yyyy-MM-dd"), false));
                    }
                }
                if (listDocument.size() > 0) {
                    documentAdapter.setList(listDocument);
                    mDataBinding.rvDocumentList.setVisibility(View.VISIBLE);
                    mDataBinding.tvDocumentNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvDocumentList.setVisibility(View.GONE);
                    mDataBinding.tvDocumentNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    //删除文档
    private void deleteDoc() {

        showDialog(getString(R.string.delete_ing));
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                for (String uri : listUri) {
                    mContext.getContentResolver().delete(Uri.parse(uri), null, null);
                }
                emitter.onNext("");
            }

            @Override
            public void accept(String path) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        cancelEdit();
                        getData();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                }, 500);
            }
        });
    }

    //取消编辑
    private void cancelEdit() {
        listUri.clear();
        isEdit = false;
        mDataBinding.ivDocumentBack.setVisibility(View.VISIBLE);
        mDataBinding.ivDocumentEdit.setVisibility(View.VISIBLE);
        mDataBinding.tvDocumentDelete.setVisibility(View.GONE);
        documentAdapter.setEdit(isEdit);
        for (MyDocumentBean bean : documentAdapter.getValidData()) {
            bean.setSelect(false);
        }
        documentAdapter.notifyDataSetChanged();
    }

    //跳转到预览文档应用
    private void gotoPreviewDoc(String selUri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setType("application/pdf"); // 设置要打开的文档类型（PDF格式）
        List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(intent, 0);
        if (resolveInfos != null && !resolveInfos.isEmpty()) {
            // 设备上至少安装了一个支持打开PDF文档的应用程序
            Uri uri = Uri.parse(selUri);
            Intent intent2 = new Intent(Intent.ACTION_VIEW);
            intent2.setData(uri);
            startActivity(intent2);
        } else {
            // 设备上没有安装任何支持打开PDF文档的应用程序
            ToastUtils.showShort(R.string.no_preview_app);
        }
    }

}